﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient();
            modbusClient.Connect("127.0.0.1", 502);// 连接
                                                   // 一次请求
            modbusClient.UnitIdentifier = 10;


            // 后台线程
            var thread = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    // 03功能码
                    int[] values = modbusClient.ReadHoldingRegisters(1, 4);

                    this.label1.Invoke(new Action(() =>
                    {
                        this.label1.Text = values[0].ToString();
                    }));
                }
            }));

            thread.IsBackground = true;
            thread.Start();
        }
    }
}
